package com.k2data.k2app.service.pas04;


import com.k2data.k2app.HttpClientUtil;
import com.k2data.k2app.common.K2Assert;
import com.k2data.k2app.common.MyConstant;
import com.k2data.k2app.domain.pasObject.*;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.util.DateFormatterUtil;
import com.k2data.k2app.util.JsonUtils;
import com.k2data.k2app.util.UUIDUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 从pas取回来的数据
 * Created by clb on 17-3-30.
 */
@Log4j2
@Service
public class Pas04ProjectService extends Pas04Basic {
	@Autowired
	private MyConstant myConstant;

	/**
	 * 创建pas项目
	 */
	public String createProject(PasProject pasProject) throws Exception{
		String projId = pasProject.getProjId();
		pasProject.setProjId(null);
		String infoError = HttpClientUtil.onPostObject(getProjectUrl()+"?projId="+ projId,pasProject);
		Map  map = JsonUtils.convertJsonStrToMap(infoError);
		String result = map.get("result") == null?"":map.get("result").toString();
		return result;
	}

	/**
	 * 编辑pas项目
	 */
	public String editProject(PasProject pasProject) throws Exception{
		String projId = pasProject.getProjId();
		pasProject.setProjId(null);
		String infoError = HttpClientUtil.onPutObject(getProjectUrl()+"/"+projId,pasProject);
		Map  map = JsonUtils.convertJsonStrToMap(infoError);
		String result = map.get("result") == null?"":map.get("result").toString();
		return result;
	}

	/**
	 * 获取复制的项目
	 */
	public PasProject copyPasProject(Long modelId)  throws Exception{
		Optional<PasProject> project1 = Optional.ofNullable(getPasProject(modelId));
		if(project1.isPresent()){
			String now = DateFormatterUtil.getNow(DateFormatterUtil.dateTimeFormatter1);
			String newProjName = project1.get().getProjName()+"_"+modelId+"_"+now;
			String projId =  UUIDUtils.uuid();
			String infoError = getFromPas(getProjectUrl()+"/copy?id="+modelId+"&newProjName="+newProjName+"&projId="+ projId);
			PasProject pasProject = jsonToPasProject(infoError);
			pasProject.setProjId(projId);
			return pasProject;
		}
		return null;
	}

	/**
	 * 删除项目
	 */
	public void deleteProjectById(Long projectId) throws Exception{
		String infoError = HttpClientUtil.onDelete(getProjectUrl()+"/"+projectId);
		Map<String, Object> resultMap = JsonUtils.convertJsonStrToMap(infoError);
		K2Assert.isExceptionByPas(resultMap);
	}

	/**
	 * 运行项目
	 * @param projectId 项目id
	 * @param param	运行条件
	 * @throws Exception
	 */
	public String runProject(Long projectId,Map<String,String> param) throws Exception {
		String infoError = HttpClientUtil.onPost(getRunJobUrl()+projectId,param);
		Map<String, Object> resultMap = JsonUtils.convertJsonStrToMap(infoError);
		K2Assert.isExceptionByPas(resultMap);
		Map<String,Object> jobIdMap = JsonUtils.convertJsonStrToMap(resultMap.get("result"));
		String jobId = jobIdMap.get("jobId").toString();
		return jobId;
	}

	/**
	 * 获取pas模型对象集合
	 */
	public List<PasProject> getPasProjects() throws Exception{
		List<PasProject> list = new ArrayList<>();
		String infoError = getFromPas(getProjectUrl()+"?owner="+myConstant.getOwner()+"&page=1&size=2000");
		Map<String, Object> resultMap = JsonUtils.convertJsonStrToMap(infoError);
		Optional<Object> optional = Optional.ofNullable(resultMap.get("result"));
		if(optional.isPresent()){
			List result= JsonUtils.convertJsonStrToList(resultMap.get("result"));
			for(int i = 0;i<result.size();i++){
				Map<String, Object> project = JsonUtils.convertJsonStrToMap(result.get(i).toString());
				String id = project.get("id")==null?"":project.get("id").toString();
				PasProject pasProject = getPasProject(Long.parseLong(id));
				if(pasProject != null){
					pasProject.setProjId(id);
					list.add(pasProject);
				}
			}
		}
		return list;
	}
	/**
	 * 获取项目对象
	 * @return
	 */
	public PasProject getPasProject(Long modelId)  throws Exception{
		String infoError = getFromPas(getProjectUrl()+"/"+modelId);
		PasProject pasProject = jsonToPasProject(infoError);
		if(pasProject != null){
			pasProject.setProjId(String.valueOf(modelId));
		}
		return pasProject;
	}
	public PasProject jsonToPasProject(String infoError)  throws Exception{
		Map<String, Object> resultMap = JsonUtils.convertJsonStrToMap(infoError);
		Optional<Object> optional = Optional.ofNullable(resultMap.get("result"));
		if(optional.isPresent()) {
			PasProject pasProject = resultToPasProject(resultMap.get("result").toString());
			return pasProject;
		}
		return null;
	}
	/**
	 * pas项目转换为对象 (所有字段)
	 * @param modelJson
	 */
	public PasProject resultToPasProject(String modelJson)  throws K2ResponseException{
		Map<String, Object> project = JsonUtils.convertJsonStrToMap(modelJson);
		String projName = project.get("projName")==null?"":project.get("projName").toString();
		String fileType = project.get("fileType")==null?"":project.get("fileType").toString();
		String owner = project.get("owner")==null?"":project.get("owner").toString();
		String ownerContact = project.get("ownerContact")==null?null:project.get("ownerContact").toString();
		String createTime = project.get("createTime")==null?null:project.get("createTime").toString();
		String updateTime = project.get("updateTime")==null?null:project.get("updateTime").toString();
		String creator = project.get("creator")==null?null:project.get("creator").toString();
		String lastEditor = project.get("lastEditor")==null?null:project.get("lastEditor").toString();
		String description = project.get("description")==null?null:project.get("description").toString();
		String triggerRule = project.get("triggerRule")==null?null:project.get("triggerRule").toString();
		String quartzStartTime = project.get("quartzStartTime")==null?null:project.get("quartzStartTime").toString();
		String quartzEndTime = project.get("quartzEndTime")==null?null:project.get("quartzEndTime").toString();
		String task = project.get("task")==null?null:project.get("task").toString();
		Map taskMap = JsonUtils.convertJsonStrToMap(task);
		if(task == null){
			taskMap = new HashMap();
			taskMap.put("timed",false);
		}
		PasProject pasProject = new PasProject(null,projName,fileType,owner,ownerContact,creator,lastEditor,description,createTime,updateTime,triggerRule,quartzStartTime,quartzEndTime,taskMap,null);

		//projectConf
		Map<String, Object> projectConf = JsonUtils.convertJsonStrToMap(project.get("projectConf"));
		String dataSource = projectConf.get("dataSource")==null?null:projectConf.get("dataSource").toString();
		String dataType = projectConf.get("dataType")==null?null:projectConf.get("dataType").toString();
		String analysisType = projectConf.get("analysisType")==null?null:projectConf.get("analysisType").toString();
		String paralType = projectConf.get("paralType")==null?null:projectConf.get("paralType").toString();
		String mainR = projectConf.get("mainR")==null?null:projectConf.get("mainR").toString();
		String allR = projectConf.get("allR")==null?null:projectConf.get("allR").toString();
		String trainProjIdStr = projectConf.get("trainProjId")==null?null:projectConf.get("trainProjId").toString();
		String stmtWhere = projectConf.get("stmtWhere")==null?null:projectConf.get("stmtWhere").toString();
		String stmtTable = projectConf.get("stmtTable")==null?null:projectConf.get("stmtTable").toString();
		String hdfsPath = projectConf.get("hdfsPath")==null?null:projectConf.get("hdfsPath").toString();
		String targetFiletype = projectConf.get("targetFiletype")==null?null:projectConf.get("targetFiletype").toString();
		String customConf =  projectConf.get("customConf")==null?null:projectConf.get("customConf").toString();
		String groupCondition = projectConf.get("groupCondition")==null?null:projectConf.get("groupCondition").toString();
		String partitionInfo = projectConf.get("partitionInfo")==null?null:projectConf.get("partitionInfo").toString();
		Map customConfMap = JsonUtils.convertJsonStrToMap(customConf);
		List partitionInfoList= JsonUtils.convertJsonStrToList(partitionInfo);
		Long trainProjId = 0L;
		if(trainProjIdStr !=null ){
			trainProjId = Long.parseLong(trainProjIdStr);
		}
		ProjectConf projectConfObject = new ProjectConf(dataSource,dataType,analysisType,paralType,mainR,allR,trainProjId,stmtWhere,stmtTable,hdfsPath,targetFiletype,customConfMap,partitionInfoList,null,null);

		List<GroupCondition> groupConditionList = new ArrayList<>();
		List groupConditions= JsonUtils.convertJsonStrToList(groupCondition);
		for(int i =0;i<groupConditions.size();i++){
			Map<String, Object> groupCondition1 = JsonUtils.convertJsonStrToMap(groupConditions.get(i).toString());
			String name = groupCondition1.get("name")==null?null:projectConf.get("name").toString();
			String type = groupCondition1.get("type")==null?null:projectConf.get("type").toString();
			String groupType = groupCondition1.get("groupType")==null?null:projectConf.get("groupType").toString();
			String groups = groupCondition1.get("groups")==null?null:projectConf.get("groups").toString();

			GroupCondition groupConditionObject= new GroupCondition(name,type,groupType,null);

			//groups
			List<Group> groupObjectList = null;
			List groupsList= JsonUtils.convertJsonStrToList(groups);
			if(groupsList.size()>0){
				groupObjectList = new ArrayList<>();
			}
			for(int j =0;j<groupsList.size();j++){
				Map<String, Object> group = JsonUtils.convertJsonStrToMap(groupsList.get(i).toString());
				String group_group = group.get("group")==null?null:projectConf.get("group").toString();
				String group_groupOpr = group.get("groupOpr")==null?null:projectConf.get("groupOpr").toString();
				Group group1 = new Group(group_group,group_groupOpr);
				groupObjectList.add(group1);
			}
			groupConditionObject.setGroups(groupObjectList);
			groupConditionList.add(groupConditionObject);
		}
		projectConfObject.setGroupCondition(groupConditionList);

		//select
		List<Select> selects = null;
		String selectStr = projectConf.get("select")==null?null:projectConf.get("select").toString();
		List selectsList= JsonUtils.convertJsonStrToList(selectStr);
		if(selectsList.size()>0){
			selects = new ArrayList<>();
		}
		for(int j =0;j<selectsList.size();j++){
			Map<String, Object> group = JsonUtils.convertJsonStrToMap(selectsList.get(j).toString());
			String name = group.get("name")==null?null:group.get("name").toString();
			String type = group.get("type")==null?null:group.get("type").toString();
			Select select = new Select(name,type);
			selects.add(select);
		}
		projectConfObject.setSelect(selects);
		pasProject.setProjectConf(projectConfObject);
		return  pasProject;
	}
}
